﻿/// <reference path="/script/_references.js" />
var _UE = UE.getEditor('Detail');
var sku_value_html = "";
var skuKey;//SKU-Key
var skuValue;//SKU-Value
var data = {
    "SKUList": [],
    "CommissionList": []
};//SKU-List
var chooseSKUKey = [];//选择了的SKUKey
var chooseSKUKeyTemporary = [];
var TableData = [];//表格SKU数据
var TableCommissionData = [];
var TableSKUData = [];
var chooseSKUValue = [];//sku_value选择属性数组
var productImgS = [];//产品图片链接
var tablehead = "<th>图片</th><th>原价</th><th>出售价格</th><th>商品库存</th><th>团购价格</th><th>一级合伙人分利</th><th>二级合伙人分利</th><th>三级及以上分利</th><th>普通一级分利</th><th>普通二季分利</th><th>分利类型</th>";
///////////////
var imgs;
var branditems;
var typeitems;
var formValidEvent;
var id = QueryPageUrlString("v") != undefined ? QueryPageUrlString("v").replace("#", "") : "";//判断是否是编辑进来的

$(function () {

    GetLoadParmt(Rendering)
    $("#btn-search").on("click", function () { //保存按钮有添加和编辑
        // if (!formValidEvent.check()) { return; }
        var apiUrl = "product/insert";
        if (id > 0) {
            apiUrl = "product/upd";
        }
        var productObj = {
            Product: {}, SKUList: [], CommissionList: [],
        }
        productObj.Product = $("#tabContent1").getFormData();
        productObj.Product.Detail = _UE.getContent();
        productObj.Product.Id = id;//
        productObj.Product.ImgUrl = productImgS.join(",");
        productObj.SKUList = TableSKUData;
        productObj.CommissionList = TableCommissionData;
        //获取轮播and首页图片
        productObj.Product.ImgUrl = $("#imgurl-body>div img[data-url]").map(function () { return $(this).attr("src") }).get().join(",");
        productObj.Product.ImgCarousel = $("#imgcarousel-body>div img[data-url]").map(function () { return $(this).attr("src") }).get().join(",");
        $.http.request(apiUrl, productObj, {
            pass: function (d) {
                $.msgSucceed("操作成功");
                setTimeout(function () {
                    window.location.href = "/views/mall/product/productment/list.html";
                }, 1000);
            },
            error: function (d) {
                $.msgFall("操作失败");
            }
        });
        return;
    });
});


function Rendering() {
    if (id > 0) { //存在值的情况
        $.http.json("product/find", {Id: id}, {
            pass: function (d) {
                console.log(d)
                data.SKUList = d.SKUList;
                TableSKUData = d.SKUList;
                TableCommissionData = d.CommissionList;
                data.CommissionList = d.CommissionList;
                $.each(TableSKUData, function (i, item) {
                    item.id = i;
                });
                $.each(TableCommissionData, function (i, item) {
                    item.Id = i;
                });
                $("#tabContent1").append(template("tem-Content1", {
                    P: d.Product,
                    brand: branditems,
                    type: typeitems
                }));//渲染模板，要先渲染才能获值
                $("#ProductBrand_Id").val(d.Product.ProductBrand_Id);
                $("#PutawayState").val(d.Product.PutawayState);
                $("#NewState").val(d.Product.NewState);
                $(".enrich-drop-down").enrichGropDown({ data: typeitems, search: "TypeName", type: 2, value: d.Product.ProductType_Id });
                //渲染轮播图
                $("#imgcarousel-body").html(template("tp-imgcarousel", { imgUrl: d.Product.ImgCarousel.split(",") }));//ImgCarousel
                //渲染首页图
                $("#imgurl-body").html(template("tp-imgcarousel", { imgUrl: d.Product.ImgUrl.split(",") }));

                load();
                _UE.ready(function () {
                    _UE.setContent(d.Product.Detail);//返回的副本图片
                });
            },
            error: function (d) {
                $.msgFall(d);
            }
        });
    } else {
        $("#tabContent1").append(template("tem-Content1", {
            brand: branditems,
            type: typeitems,
            P: {}
        }));
        $(".enrich-drop-down").enrichGropDown({ data: typeitems, search: "TypeName" });
    }
    $("#Content4").append(template("tem-sku"), {}) //sku属性配置
    Uploader();
    formValidInit();
}
function formValidInit() {  //判断输入框是否为空
    var formValidData = [
        {
            key: "ProductName",
            datatype: "*",
            nullmsg: "不能为空哦",
            errormsg: "不能为空哦"
        },
        {
            key: "ProductType_Id",
            datatype: "*",
            nullmsg: "不能为空哦",
            errormsg: "不能为空哦"
        },

        {
            key: "ProductBrand_Id",
            datatype: "*",
            nullmsg: "不能为空哦",
            errormsg: "不能为空哦"
        },

        {
            key: "Features",
            datatype: "*",
            nullmsg: "不能为空哦",
            errormsg: "不能为空哦！"
        },
        {
            key: "Explain",
            datatype: "*",
            nullmsg: "不能为空哦",
            errormsg: "不能为空哦！"
        },
        {
            key: "original-price",
            datatype: "n",
            nullmsg: "不能为空哦",
            errormsg: "请正确输入！"
        },
        {
            key: "current-price",
            datatype: "n",
            nullmsg: "不能为空哦",
            errormsg: "请正确输入！"
        },
        {
            key: "inventory",
            datatype: "n",
            nullmsg: "不能为空哦",
            errormsg: "请正确输入！"
        },
    ];
    formValidEvent = $(".tem-Content1").formValid(formValidData); // 把框判断植入
}
function GetLoadParmt(result) {
    $.http.request(   //品牌、类型、供货商的存在显示 (基本信息)
        "product/parameterdata",
        null,
        {
            pass: function (d, status, xhr) {
                branditems = d.brandList;
                typeitems = d.typeList;
                result();
                skuKey = d.skuKeyList;
                skuValue = d.skuValueList;
            }
        }
    );
}

//添加轮播图片
function addCarouselPic(d) {
    if ($("#imgcarousel-body>div").length >= 5) {
        $.alert("轮播图只能最多添加5张");
        return;
    }
    $("#imgcarousel-body").append(template("tp-imgcarousel-item", { imgUrl: d }));
    $("#imgcarousel-body").sortable();
  
}
//添加首页产品图 
function addProductPic(da) {
   
    if ($("#imgurl-body>div").length >= 5) {
        $.alert("首页产品图只能最多添加5张");
        return;
    }
    $("#imgurl-body").append(template("tp-imgcarousel-item", { imgUrl: da }));
}

//删除产品图
function DeleteBanner(item) {
    $(item).parent().parent().parent().remove();
}
//上传首页图跟轮播图 0=轮播 1=首页
function addBannerImg(obj) {
    $.WebUploader({
        uploader: {
            fileNumLimit: 1,
            fileSingleSizeLimit: 150 * 1024,
            accept: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image/*'
            },
            succee: function (rs) {            
                var src = rs.Url;
                if (obj == 1) {
                    addProductPic(src);
                } else if (obj == 0) {
                    addCarouselPic(src);
                } else {
                 $(obj).parent().prev("img").attr("src", rs.Url);     
                }
                     
            }
        }
    });


}


function load() {
    GetSKUListOfKeyAndValue();//获取列表的SKU属性值Key和Value
    CreateSKUValueHtml();//创建SKUKey对应的Value模块html
    LoadSKUValueChooseStatus();//初始化列表SKU属性的Value选中状态
    LoadSKUValue();
    //初始化table
    FrameworkDataList();
    LoadTableFramework(TableData);
    chooseSKUKeyTemporary = chooseSKUKey;
}
/*上传图片*/
function Uploader() {
    $("img").click(function () {
        var obj = this;
        $.WebUploader({
            uploader: { //图片上传配置
                fileNumLimit: 1000024, // 验证文件总数量, 超出则不允许加入队列
                fileSingleSizeLimit: 1230000000, //验证单个文件大小是否超出限制,单位计算/b
                succee: function (rs) {
                    $(obj).attr("src", rs.Url);
                    $.each(TableSKUData, function (i, item) {
                        if (item.id == $(obj).parents("tr").attr("data-id")) {
                            item[$(obj).attr("data-tag")] = rs.Url;
                        }
                    });
                }
            }
        })
    });
}
/* 初始化SKUValue选中状态 */
function LoadSKUValueChooseStatus() {
    $.each(chooseSKUValue, function (i, vitem) {
        $(".panel-group input").each(function () {
            if ($(this).data("id") == vitem.id) {
                $(this).attr("checked", "checked");
            }
        });
    });
}
/* 获取SKU属性列表的SKUKey-SKUValue */
function GetSKUListOfKeyAndValue() {
    $.each(data.SKUList, function (i, item) {
        var skukeyarray = item.SkuProperty.split(";");
        $.each(skukeyarray, function (j, kitem) {
            var cstatus = 0;
            $.each(chooseSKUKey, function (k, citem) {
                if (kitem.split(":")[0] == citem) {
                    cstatus = 1;
                    return;
                }
            });
            if (cstatus == 0) {
                chooseSKUKey.push(kitem.split(":")[0]);
            } else { cstatus = 0; }

            var vstatus = 0;
            $.each(chooseSKUValue, function (k, vitem) {
                if (kitem.split(":")[1] == vitem.id) {
                    vstatus = 1;
                    return;
                }
            });
            if (vstatus == 0) {
                chooseSKUValue.push({ kid: kitem.split(":")[0], id: kitem.split(":")[1] });
            } else { vstatus = 0; }
        });
    });
}
/* 当选择SKU-Key时初始化对应属性列表 */
function LoadSKUKey(obj) {
    chooseSKUKeyTemporary = [];
    $(".layui-layer-content input").each(function (i, item) {
        if ($(this).is(':checked')) {
            chooseSKUKeyTemporary.push($(this).attr("data-value"));
        }
    });
}
/* 当选择SKU-Value时初始化对应属性列表 */
function LoadSKUValue() {
    var html = "";
    $.each(chooseSKUKey, function (i, item) {
        $.each(skuKey, function (j, kitem) {
            if (item == kitem.Id) {
                html += "<th>" + kitem.AttrName + "</th>";
            }
        })
    });
    html += tablehead;
    $(".skutable tbody").html("");
    $(".skutable tr").html("");
    $(".skutable tr").append(html);
}
/* 操作SKU选项对应数据做出变化 */
function EditSKUOfData(obj) {
    chooseSKUValue = [];
    var selectObj = $(".panel-group input[type='checkbox']:checked");
    $.each(selectObj, function () {
        chooseSKUValue.push({ id: $(this).attr("data-id"), kid: $(this).attr("data-kid") });
    });
    var skus = [];
    var index = 0;
    $(".skuvalue" + chooseSKUKey[0] + "[type='checkbox']:checked").each(function () {
        skus.push($(this).attr("data-kid") + ":" + $(this).attr("data-id"));
    });
    if (chooseSKUKey.length > (index + 1)) {
        CreateDateList(skus, index + 1);
    } else {
        CreateDateList(skus, index);
    }
}
//每次修改sku属性重新生成列表
function CreateDateList(obj, index) {
    TableCommissionData = [];
    TableSKUData = [];
    TableData = [];
    // BEGIN 这里是遍历出所有的SKU组合值
    var skus = [];
    var tempSkus = [];
    $(".skuvalue" + chooseSKUKey[index] + "[type='checkbox']:checked").each(function () {
        skus.push($(this).attr("data-kid") + ":" + $(this).attr("data-id"));
    });
    $.each(obj, function (i, item) {
        $.each(skus, function (j, item2) {
            tempSkus.push(item + ";" + item2);
        });
    });
    if (index > 0) {
        skus = tempSkus;
    }
    //END
    if (chooseSKUKey.length > (index + 1)) {
        CreateDateList(skus, index + 1);
    } else {
        $.each(skus, function (i, item) {
            var objTemplateTemporary = {
                id: i, SkuPropertyPic: $("#LoadSkuPropertyPic").attr("src"), OriginalPrice: $("#LoadOriginalPrice").val(), SellPrice: $("#LoadSellPrice").val(), Inventory: $("#LoadInventory").val(), GroupPrice: $("#LoadGroupPrice").val(), SkuProperty: item,
                CommissionType: $("#LoadCommissionType").val(), PartnerLevelOneCommission: $("#LoadPartnerLevelOneCommission").val(),
                PartnerLevelTwoCommission: $("#LoadPartnerLevelTwoCommission").val(), PartnerLevelOtherCommission: $("#LoadPartnerLevelOtherCommission").val(),
                CommonLevelOneCommission: $("#LoadCommonLevelOneCommission").val(), CommonLevelTwoCommission: $("#LoadCommonLevelTwoCommission").val()
            };
            var SKUTemplateTemporary = { id: i, SkuName: "", SkuPropertyPic: $("#LoadSkuPropertyPic").attr("src"), OriginalPrice: $("#LoadOriginalPrice").val(), SellPrice: $("#LoadSellPrice").val(), Inventory: $("#LoadInventory").val(), GroupPrice: $("#LoadGroupPrice").val(), SkuProperty: item };
            var CommissionTemplateTemporary = {
                id: i, SKU: item, CommissionType: $("#LoadCommissionType").val(), PartnerLevelOneCommission: $("#LoadPartnerLevelOneCommission").val(),
                PartnerLevelTwoCommission: $("#LoadPartnerLevelTwoCommission").val(), PartnerLevelOtherCommission: $("#LoadPartnerLevelOtherCommission").val(),
                CommonLevelOneCommission: $("#LoadCommonLevelOneCommission").val(), CommonLevelTwoCommission: $("#LoadCommonLevelTwoCommission").val()
            }

            var skuKeyStrArray = item.split(";");
            var skuName = "";
            $.each(skuKeyStrArray, function (j, ksitem) {
                var skuValueStrArray = ksitem.split(":");
                var attrName = "";
                var value = "";
                $.each(skuKey, function (k, skitem) {
                    if (skuValueStrArray[0] == skitem.Id) { attrName = skitem.AttrName; }
                });
                $.each(skuValue, function (k, svitem) {
                    if (skuValueStrArray[1] == svitem.Id) { value = svitem.AttrValue; }
                });
                skuName += value + "/";
                objTemplateTemporary[attrName] = value;
            });
            if (skuName.length > 0) { skuName = skuName.substr(0, skuName.length - 1); }
            SKUTemplateTemporary.SkuName = skuName;
            TableCommissionData.push(CommissionTemplateTemporary);
            TableSKUData.push(SKUTemplateTemporary);
            TableData.push(objTemplateTemporary);
        });
        //循环把新增添加
        $.each(TableData, function (i, item) {
            $.each(TableData, function (j, item2) {
                if (item.SkuProperty == item2.SkuProperty) {
                    TableData[i] = item2;
                }
            });
        });
        LoadTableFramework(TableData);
    }
}
function LoadTableObjTemplate() {
    var objTemplate = { id: 0, SkuPropertyPic: "", OriginalPrice: 0, SellPrice: 0, Inventory: 0, GroupPrice: 0, SkuProperty: "" };
    $.each(chooseSKUKey, function (i, cskitem) {
        $.each(skuKey, function (j, skitem) {
            if (cskitem == skitem.Id) {
                objTemplate[skitem.AttrName] = "";
            }
        });
    });
}
/* 生成选中skuvalue的html内容 */
function eachSKUValueHtml(skuKeyId) {
    var sku_value_htmls = "";
    $.each(skuKey, function (i, item) {
        if (item.Id == skuKeyId) {
            var html = template("SkuValue", { item: item });
            sku_value_htmls += html;
        }
    });
    var skuValueHtml = "";
    $.each(skuValue, function (i, item) {
        if (item.ProductAttrKey_Id == skuKeyId) {
            skuValueHtml += template("SkuValueCheckBox", { item: item });
        }
    });
    sku_value_html += sku_value_htmls.replace("[[sku_value" + skuKeyId + "]]", skuValueHtml);
}
/* 生成skuvalueHTML */
function CreateSKUValueHtml() {
    //生成skuvalueHTML
    $.each(chooseSKUKey, function (i, item) {
        eachSKUValueHtml(item);
    });
    //绑定并且清空全局字段sku_value_html
    $(".panel-group").html(sku_value_html); sku_value_html = "";
}
/* 显示SKUList窗体 */
function ShowSKUList() {
    layer.open({
        type: 1,
        btn: ['确定', '取消'],
        title: '配置SKU-Key',
        shadeClose: false,
        offset: '150px',
        shade: [0.8, '#000'],
        maxmin: false, //开启最大化最小化按钮
        area: ['893px', '300px'],
        content: '',
        btn1: function (index, layero) {
            var result = CompareChooseSKUKey(chooseSKUKey, chooseSKUKeyTemporary);
            if (result > 0 && confirm("是否重新配置！")) {
                chooseSKUKey = chooseSKUKeyTemporary;
                CreateSKUValueHtml();
                //关闭窗口
                layer.closeAll();
                LoadSKUValue();
                LoadTableObjTemplate();
            } else {
                //关闭窗口
                layer.closeAll();
            }
        },
        btn2: function (index, layero) {
            sku_value_html = "";
        },
        cancel: function (index, layero) {
            sku_value_html = "";
        },
        success: function (layero, index) {
            //初始化复选框
            $.each(skuKey, function (i, item) {
                $(".layui-layer-content").append(template("ConfigCheckBox", { item: item }));
                $(".layui-layer-content .checkbox ").css("float", "left").css("margin-top", "10px");
            });
            //打开窗体初始化选中状态
            $.each(chooseSKUKey, function (i, item) {
                $(".sku_key" + item).attr("checked", "checked");
            });
        }
    });

}
/* 匹配两个数组不重复的个数 */
function CompareChooseSKUKey(array, array2) {
    var sum = 0;
    for (var i = 0; i < array.length; i++) {
        var stra = array[i];
        var count = 0;
        for (var j = 0; j < array2.length; j++) {
            var strb = array2[j];
            if (stra == strb) {
                sum++;
            }
        }
    }
    if (sum == array.length && sum == array2.length) {
        return 0;
    }
    return 1;
}
/* 格式化数据列表 */
function FrameworkDataList() {
    $.each(data.SKUList, function (i, item) {
        var skuArray = item.SkuProperty.split(";");
        var obj = {
            id: i, SkuPropertyPic: item.SkuPropertyPic, OriginalPrice: item.OriginalPrice, SellPrice: item.SellPrice, Inventory: item.Inventory, GroupPrice: item.GroupPrice, SkuProperty: item.SkuProperty,
            CommissionType: "2", PartnerLevelOneCommission: "1",
            PartnerLevelTwoCommission: "1", PartnerLevelOtherCommission: "1",
            CommonLevelOneCommission: "1", CommonLevelTwoCommission: "1"
        };
        $.each(data.CommissionList, function (k, citem) {
            if (citem.SKU == item.SkuProperty) {
                obj.CommissionType = citem.CommissionType;
                obj.PartnerLevelOneCommission = citem.PartnerLevelOneCommission;
                obj.PartnerLevelTwoCommission = citem.PartnerLevelTwoCommission;
                obj.PartnerLevelOtherCommission = citem.PartnerLevelOtherCommission;
                obj.CommonLevelOneCommission = citem.CommonLevelOneCommission;
                obj.CommonLevelTwoCommission = citem.CommonLevelTwoCommission;
            }
        });
        $.each(skuArray, function (j, sitem) {
            $.each(skuValue, function (k, vitem) {
                if (vitem.ProductAttrKey_Id == sitem.split(":")[0] && vitem.Id == sitem.split(":")[1]) {
                    $.each(skuKey, function (m, kitem) {
                        if (vitem.ProductAttrKey_Id == kitem.Id) {
                            obj[kitem.AttrName] = vitem.AttrValue;
                        }
                    });
                }
            });
        });
        TableData.push(obj);
    });
}
/* 加载表格格式 */
function LoadTableFramework(TableData) {
    var SKUTemporary = [];
    $.each(chooseSKUKey, function (i, item) {
        $.each(skuKey, function (m, kitem) {
            if (item == kitem.Id) {
                SKUTemporary.push(kitem);
            }
        });
    });
    var tablehtml = "";
    $.each(TableData, function (i, item) {
        var skus = "";
        $.each(SKUTemporary, function (m, kitem) {
            skus += "<td>" + item[kitem.AttrName] + "</td>";
        });
        item.skus = skus;
        tablehtml += template("Table", { item: item });
    });
    $(".skutable tbody").html("");
    $(".skutable tbody").append(tablehtml);
    $(".skutable .form-control").blur(function () {
        var id = $(this).parents("tr").data("id");
        var value = $(this).val();
        var obj = this;
        var tag = $(this).attr("data-tag");
        $.each(TableSKUData, function (i, item) {
            if (item.id == id && item.hasOwnProperty(tag)) {
                item[$(obj).data("tag")] = value;
            }
        });
        $.each(TableCommissionData, function (i, item) {
            if (item.Id == id && item.hasOwnProperty(tag)) {
                item[$(obj).data("tag")] = value;
            }
        });
    });
    Uploader();
}
